<template>
  <div>
    <h2>学生列表</h2>
    <table class="table">
      <thead>
        <tr>
          <th>编码</th>
          <th>姓名</th>
          <th>性别</th>
          <th>专业</th>
          <th>电话</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in computedList" :key="item.id">
          <td>
            <input type="checkbox" :value="item.id" v-model="selectIds" />
          </td>
          <td>{{ item.name }}</td>
          <td>{{ item.sex }}</td>
          <td>{{ item.major }}</td>
          <td>{{ item.tel }}</td>
          <td>
            <span @click="handleDeleteRow(item.id)" class="iconfont icon-del"
              >删除</span
            >
          </td>
        </tr>
      </tbody>
    </table>
    <div class="tfoot">
      <span class="span-type">{{ leftCount }}未选</span>
      <span @click="handleType(1)" :class="getClass(1)">全部</span>
      <span @click="handleType(2)" :class="getClass(2)">未选中</span>
      <span @click="handleType(3)" :class="getClass(3)">选中</span>
      <span @click="handleDelete" class="span-type">删除选中</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits } from "vue";

const props = defineProps({
  listData: {
    type: Array,
    required: true,
  },
});

// 选中项
const selectIds = ref([]);
const emits = defineEmits(["delete-row", "delete"]);

// 选中的项目
const type = ref(1);

// 点击行后面的删除，删除当前行
function handleDeleteRow(id: number) {
  emits("delete-row", id);

  // 把存储选中项的也删除
  const index = selectIds.value.findIndex((v) => v == id);
  if (index != -1) {
    selectIds.value.splice(index, 1);
  }
}

function getClass(value: number) {
  return {
    // 当对象的属性值为true的时候，表示有该属性名的class值
    "span-type-active": type.value == value,
    "span-type": true,
  };
}

function handleType(value: number) {
  type.value = value;
}

function handleDelete() {
  // 触发自定义事件，让父组件完成删除
  emits("delete", selectIds.value);

  // 把selectIds也清空
  selectIds.value.length = 0;
}

const computedList = computed(() => {
  // console.log("selectIds = ",selectIds);
  switch (type.value) {
    // 选中
    case 3: {
      return props.listData.filter(
        (v1: any) => selectIds.value.findIndex((v2) => v2 == v1.id) != -1
      );
    }
    // 未选中
    case 2: {
      return props.listData.filter(
        (v1: any) => selectIds.value.findIndex((v2) => v2 == v1.id) == -1
      );
    }
    default:
      return props.listData;
  }
});

const leftCount = computed(
  () => props.listData.length - selectIds.value.length
);
</script>

<style scoped lang="scss">
.table {
  width: 100%;
}
.tfoot {
  .span-type {
    padding: 5px;
  }

  .span-type-active {
    color: #fff;
    background-color: #ac1111;
  }
}
</style>